package tangjl.async.websocket;

import org.apache.log4j.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * 功能说明：websocket处理类, 使用J2EE7的标准
 *
 * @author tangjialin on 2017-12-17.
 */
@ServerEndpoint("/websocket/{uniqueIdentification}")
public class WebsocketEndPoint {

    private static Logger log = Logger.getLogger(WebsocketEndPoint.class);

    /**
     * 开启链接
     *
     * @param uniqueIdentification
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("uniqueIdentification") String uniqueIdentification,
                       Session session) {
        log.info("Websocket Start Connecting:" + uniqueIdentification);
        SessionUtils.put(uniqueIdentification, session);
    }

    /**
     * 接收客户端消息
     *
     * @param uniqueIdentification
     * @param message
     * @return
     */
    @OnMessage
    public String onMessage(@PathParam("uniqueIdentification") String uniqueIdentification,
                            String message) {
        return "Got your message (" + message + ").Thanks !";
    }

    /**
     * 链接异常
     *
     * @param uniqueIdentification
     * @param session
     */
    @OnError
    public void onError(@PathParam("uniqueIdentification") String uniqueIdentification,
                        Throwable throwable,
                        Session session) {
        log.info("Websocket Connection Exception:" + uniqueIdentification);
        log.info(throwable.getMessage(), throwable);
        SessionUtils.remove(uniqueIdentification);
    }

    /**
     * 关闭连接
     *
     * @param uniqueIdentification
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("uniqueIdentification") String uniqueIdentification,
                        Session session) {
        log.info("Websocket Close Connection:" + uniqueIdentification);
        SessionUtils.remove(uniqueIdentification);
    }


}